<template>
  <div class="order">
    <!-- <p>订单管理</p> -->
    <div class="content">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单编号：">
              <el-input
                v-model="form.orderNumber"
                placeholder="订单编号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="下单时间：">
              <el-date-picker
                clearable
                v-model="form.data"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="订单状态：">
              <el-select
                v-model="form.status"
                clearable
                placeholder="请选择订单状态"
              >
                <el-option label="待付款" :value="1"></el-option>
                <el-option label="待发货" :value="2"></el-option>
                <el-option label="待收货" :value="3"></el-option>
                <el-option label="待评价" :value="4"></el-option>
                <el-option label="成功" :value="5"></el-option>
                <el-option label="失败" :value="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 按钮 -->
      <div class="btn">
        <el-button type="primary" icon="el-icon-search" @click="initData"
          >搜索</el-button
        >
        <el-button type="primary" @click="exportOrder"
          >导出待发货订单</el-button
        >
        <el-button type="primary">导出销售记录</el-button>
        <el-button>清空</el-button>
      </div>

      <!-- 表格数据 -->
      <div class="item">
        <span>商品</span>
        <span>成交单价/购买数量</span>
        <span>实付金额</span>
        <span>支付方式</span>
        <span>订单状态</span>
        <span>操作</span>
      </div>
      <div class="table" v-for="(item, index) in list" :key="index">
        <div class="tableContent">
          <div class="top">
            <span>订单编号:{{ item.orderNumber }}</span>
            <span>下单时间:{{ item.updateTime }}</span>
          </div>

          <div class="middle" v-for="(items, indexs) in item.orderItems" :key="indexs">
            <div class="first">
              <div class="firstItem">
                <div class="itemLeft">
                  <img :src="items.pic" alt="" />
                </div>
                <div class="itemRight">
                  <div class="rightLeft">
                    {{ items.prodName }}
                    <p v-if="items.skuName != ''">{{ items.skuName }}</p>
                  </div>
                  <div class="rightRight">
                    <div>￥{{ items.price }}</div>
                    <div>x{{ items.prodCount }}</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="other">
              <p style="color: #f00">￥{{ items.price }}</p>
              <p v-if="item.freightAmount != ''">
                (含运费:￥{{ item.freightAmount }})
              </p>
              <p>共{{ items.prodCount }}件</p>
            </div>
            <div class="other">
              <p v-if="items.payType == null">手动代付</p>
              <p v-if="items.payType == 1">微信支付</p>
            </div>
            <div class="other">
              <p v-if="item.status == 1">待付款</p>
              <p v-if="item.status == 2">待发货</p>
              <p v-if="item.status == 3">待收货</p>
              <p v-if="item.status == 4">待评价</p>
              <p v-if="item.status == 5">成功</p>
              <p v-if="item.status == 6">失败</p>
            </div>
            <div class="other">
              <p class="visit" @click="visit(item)">查看</p>
            </div>
          </div>
        </div>

        <div class="bottom">
          <span>备注:</span>
        </div>
      </div>

      <!-- 分页 -->
      <pagination
        :total="obj.total"
        @handleSize="handleSizeChange"
        @handleCurrent="handleCurrentChange"
      ></pagination>

      <!-- 模态框 -->
      <el-dialog title="查看" :visible.sync="dialogVisible" width="70%">
        <div class="top" v-if="detailList.orderNumber != ''">
          订单编号：{{ detailList.orderNumber }}
        </div>

        <div class="step">
          <el-steps :active="active" align-center>
            <el-step title="提交订单"></el-step>
            <el-step
              title="买家已付款"
              :description="detailList.createTime"
            ></el-step>
            <el-step
              title="卖家已发货"
              :description="detailList.dvyTime"
            ></el-step>
            <el-step title="买家已收货"></el-step>
          </el-steps>
        </div>

        <!-- 按钮状态 -->
        <div class="status">
          <div class="statusLeft">
            <span>订单状态：</span>
            <el-button
              type="warning"
              plain
              v-if="detailList.status == 1 && detailList != ''"
              >待付款</el-button
            >
            <el-button
              type="warning"
              plain
              v-if="detailList.status == 2 && detailList != ''"
              >待发货</el-button
            >
            <el-button
              type="warning"
              plain
              v-if="detailList.status == 3 && detailList != ''"
              >待收货</el-button
            >
            <el-button
              type="warning"
              plain
              v-if="detailList.status == 4 && detailList != ''"
              >待评价</el-button
            >
            <el-button
              type="success"
              plain
              v-if="detailList.status == 5 && detailList != ''"
              >成功</el-button
            >
            <el-button
              type="danger"
              plain
              v-if="detailList.status == 6 && detailList != ''"
              >失败</el-button
            >
          </div>
          <div class="statusRight">
            <el-button
              type="primary"
              plain
              v-if="detailList.status == 2 && detailList != ''"
              @click="confirm"
              >发货</el-button
            >
          </div>
        </div>

        <!-- 表格 -->
        <div class="tables">
          <div class="tabLeft">
            <p>
              <img src="@/assets/car.png" alt="" />
              <span>买家付款后才可以发货</span>
            </p>

            <div class="addr">
              <div class="addrLeft">
                <p>
                  <img src="@/assets/addr.png" alt="" /> <span>收货人：</span>
                </p>
              </div>

              <div class="addrRight">
                <span v-if="detailList != ''">{{
                  detailList.userAddrOrder.receiver
                }}</span>
              </div>
            </div>

            <div class="addr">
              <div class="addrLeft">
                <p>
                  <span>手机：</span>
                </p>
              </div>

              <div class="addrRight">
                <span v-if="detailList != ''">{{
                  detailList.userAddrOrder.mobile
                }}</span>
              </div>
            </div>

            <div class="addr">
              <div class="addrLeft">
                <p>
                  <span>收货地址：</span>
                </p>
              </div>

              <div class="addrRight">
                <span v-if="detailList != ''"
                  >{{ detailList.userAddrOrder.province }}
                  {{ detailList.userAddrOrder.city }}
                  {{ detailList.userAddrOrder.area }}
                  {{ detailList.userAddrOrder.addr }}</span
                >
              </div>
            </div>

            <div class="coll">
              <img src="@/assets/coll.png" alt="" />
              <span>不开发票</span>
            </div>
          </div>

          <div class="tabRight">
            <p>
              <img src="@/assets/buyer.png" alt="" />
              <span>买家：</span>
            </p>

            <div>
              <img src="@/assets/mess.png" alt="" />
              <span>买家备注：</span>
            </div>
          </div>
        </div>

        <!-- 商品 -->
        <div class="shop">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="date" label="商品" width="560">
              <template slot-scope="scope">
                <div class="all">
                  <div class="tableLeft">
                    <img :src="scope.row.pic" alt="" />
                  </div>
                  <div class="tableRight">
                    <p>{{ scope.row.prodName }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="price"
              label="单价"
              width="180"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="prodCount"
              label="数量"
              width="180"
            >
            </el-table-column>
            <el-table-column align="center" prop="address" label="总价">
              <template slot-scope="scope">
                {{ scope.row.price * scope.row.prodCount }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="itemright">
          <p>
            <span>商品总价:</span>
            <span v-if="detailList != ''">￥{{ detailList.total }}</span>
          </p>

          <p>
            <span>商品总价:</span>
            <span v-if="detailList != ''">￥{{ detailList.actualTotal }}</span>
          </p>
        </div>

        <!-- 日志 -->
        <div class="log">
          <h3>订单日志</h3>
          <p style="color: skyblue" v-if="detailList != ''">
            {{ detailList.updateTime }} 订单更新(成功)
          </p>
        </div>
      </el-dialog>

      <!-- 内层模态框 -->
      <el-dialog
        title="选择发货地址"
        :visible.sync="dialogVisibleInsert"
        width="40%"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="快递公司" prop="dvyId">
            <el-select v-model="ruleForm.dvyId" placeholder="请选择">
              <el-option
                :label="item.dvyName"
                :value="item.dvyId"
                v-for="(item, index) in labelList"
                :key="item.dvyId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="快递单号" prop="dvyFlowId">
            <el-input v-model="ruleForm.dvyFlowId"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleInsert = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 导出模态框 -->
      <el-dialog
        title="请输入发货信息"
        :visible.sync="dialogVisibleExcel"
        width="40%"
      >
        <el-form
          :model="ruleFormExcel"
          :rules="rules"
          ref="ruleFormExcel"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="发件人姓名" prop="consignmentName">
            <el-input v-model="ruleFormExcel.consignmentName"></el-input>
          </el-form-item>

          <el-form-item label="发货人手机号" prop="consignmentMobile">
            <el-input v-model="ruleFormExcel.consignmentMobile"></el-input>
          </el-form-item>

          <el-form-item label="发货地址" prop="consignmentAddr">
            <el-input v-model="ruleFormExcel.consignmentAddr"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleExcel = false">取 消</el-button>
          <el-button type="primary" @click="confirmExcel">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import { List } from '@/api/member.js'
import pagination from "@/components/pagination.vue";
import * as XLSX from "xlsx"; // 批量导出
export default {
  components: {
    pagination,
  },
  data() {
    return {
      dialogVisible: false,
      dialogVisibleInsert: false,
      dialogVisibleExcel: false,
      form: {
        orderNumber: "",
        data: "",
        status: "",
      },
      ruleForm: {
        dvyId: "",
        dvyFlowId: "",
      },
      ruleFormExcel: {
        consignmentName: "",
        consignmentMobile: "",
        consignmentAddr: "",
      },
      export: {
        current: 1,
        size: 100,
        total: 0,
      },
      exportList: [],
      active: 0,
      idx: "",
      rows: "",
      tableData: [],
      detailList: [],
      list: [],
      labelList: [],
      obj: {
        current: 1,
        size: 10,
        total: 0,
      },
      f: false,
      rules: {
        dvyFlowId: [{ required: true, message: "不能为空", trigger: "blur" }],
        consignmentName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        consignmentMobile: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        consignmentAddr: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
      },
      allList: [],
    };
  },
  methods: {
    // 初始化
    initData() {
      this.$axios
        .get("/api/order/order/page", {
          params: {
            current: this.obj.current,
            size: this.obj.size,
            orderNumber: this.form.orderNumber,
            startTime: this.form.data[0],
            endTime: this.form.data[1],
            status: this.form.status,
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          // console.log(res,"Res");
          this.list = res.data.data.records;
          // console.log(this.list,"list");

          for (let index = 0; index < res.data.data.records.length; index++) {
            const ele = res.data.data.records[index];
            this.allList.push({
              actualTotal: ele.actualTotal,
              productNums: ele.productNums,
              freightAmount: ele.freightAmount,
              payType: ele.payType,
              status: ele.status,
            });
          }
          console.log(this.allList, "this.allList");
          this.obj.total = res.data.data.total;
        });
      // console.log(this.list, "this.list");
      
    },
    // 导出待发货数据
    exportData() {
      this.$axios
        .get("/api/order/order/page", {
          params: {
            current: this.export.current,
            size: this.export.size,
            status: 2,
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then(async (res) => {
          this.export.total = res.data.data.total;

          const totalPage = Math.ceil(this.export.total / this.export.size);

          for (let page = 1; page <= totalPage; page++) {
            const res = await this.$axios.get("/api/order/order/page", {
              params: {
                current: page,
                size: this.export.size,
                status: 2,
              },
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            });
            this.exportList = this.exportList.concat(res.data.data.records);
          }
          console.log(this.exportList, "exportList");
        });
    },

    // 分页开始
    handleSizeChange(val) {
      console.log(val, "接收");
      // 当我点击每页多少条的时候赋值并重新渲染页面
      this.obj.size = val;
      this.initData();
    },
    handleCurrentChange(val) {
      console.log(val, "接收");
      // 当我点击页码的时候将页码赋值给变量并重新渲染页面
      this.obj.current = val;
      this.initData();
    },
    // 分页结束

    // 查看
    visit(row) {
      console.log(row, "row");
      this.rows = row;
      this.idx = row.orderNumber;
      this.dialogVisible = true;
      if (row.status == 1 || row.status == 6) {
        this.active = 0;
      } else if (row.status == 2) {
        if (this.f == false) {
          this.active = 2;
        } else {
          this.active = 3;
        }
      } else if (row.status == 3) {
        this.active = 3;
        console.log(123);
      } else if (row.status == 5) {
        this.active = 4;
      }

      this.$axios
        .get(`/api/order/order/orderInfo/${row.orderNumber}`, {
          params: {
            t: new Date().getTime(),
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          // console.log(res.data.data.records, "res");
          this.detailList = res.data.data;
          this.tableData = res.data.data.orderItems;
        });
    },

    // 发货
    confirm() {
      this.dialogVisibleInsert = true;
      this.$axios
        .get("/api/admin/delivery/list", {
          params: {
            t: new Date().getTime(),
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.labelList = res.data.data;
          console.log(this.labelList, "labelList");
        });
    },

    // 确定发货
    submit() {
      this.f = true;
      this.$axios({
        url: "/api/order/order/delivery",
        method: "PUT",
        data: {
          dvyFlowId: this.ruleForm.dvyFlowId,
          dvyId: this.ruleForm.dvyId,
          orderNumber: this.idx,
          t: new Date().getTime(),
        },
        headers: {
          Authorization: localStorage.getItem("token"),
        },
      }).then((res) => {
        if (res.data.code == "00000") {
          this.$message({
            message: "发货成功",
            type: "success",
          });
          setTimeout(() => {
            this.dialogVisibleInsert = false;
          }, 1000);
          this.visit(this.rows);
        }
      });
    },

    // 导出待发货订单
    exportOrder() {
      this.dialogVisibleExcel = true;
    },
    // 导出确定
    confirmExcel() {
      this.$axios
        .get("/api/order/order/page", {
          params: {
            t: new Date().getTime(),
            consignmentName: this.ruleFormExcel.consignmentName,
            consignmentMobile: this.ruleFormExcel.consignmentMobile,
            consignmentAddr: this.ruleFormExcel.consignmentAddr,
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.$confirm("此操作将导出excel表格, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              // console.log(this.tableData,'tableData');

              // 定义表头
              const headers = [
                "订单编号",
                "收件人",
                "手机",
                "收货地址",
                "商品名称",
                "数量",
                "发件人姓名",
                "发件人手机号",
                "发货地址",
                "备注",
              ]; // 将表格数据转换为工作表数据
              const worksheetData = [
                headers, // 第一行为表头
                ...this.exportList.map((item) => {
                  return [
                    item.orderNumber || "",
                    item.userAddrOrder.receiver || "",
                    item.userAddrOrder.mobile || "",
                    item.userAddrOrder.province +
                      item.userAddrOrder.city +
                      item.userAddrOrder.area +
                      item.userAddrOrder.addr || "",
                    item.prodName || "",
                    item.orderItems[0].prodCount || "",
                    this.ruleFormExcel.consignmentName || "",
                    this.ruleFormExcel.consignmentMobile || "",
                    this.ruleFormExcel.consignmentAddr || "",
                    item.remarks || "",
                  ];
                }),
              ]; // 创建工作表

              const worksheet = XLSX.utils.aoa_to_sheet(worksheetData); // 创建工作簿

              const workbook = XLSX.utils.book_new();
              XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1"); // 导出 Excel 文件

              XLSX.writeFile(workbook, "导出待发货订单.xlsx"); // 提示导出成功

              this.$message({
                type: "success",
                message: "导出成功！",
              });
              this.dialogVisibleExcel = false;
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消导出",
              });
            });
        });
    },
  },
  mounted() {
    this.initData();
    this.exportData();
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/order.scss";
</style>